package it.fuesi.synoutils.services.tasks.search;

import android.util.Log;

import it.fuesi.synoutils.adapters.BTSearchAdapter;
import it.fuesi.synoutils.constants.ApiErrorCode;
import it.fuesi.synoutils.model.base.ErrorObject;
import it.fuesi.synoutils.model.btsearch.BTSearchClientParameters;
import it.fuesi.synoutils.model.btsearch.BTSearchResultsDataObject;
import it.fuesi.synoutils.model.btsearch.BTSearchResultsListResponse;
import it.fuesi.synoutils.model.btsearch.BTSearchStartResponse;
import it.fuesi.synoutils.services.client.BTSearchClient;
import it.fuesi.synoutils.services.client.ServiceClientFactory;
import it.fuesi.synoutils.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class BTSearchTask extends BaseTask<BTSearchResultsListResponse, BTSearchResultsDataObject, BTSearchClientParameters> {

    private static final String TAG = BTSearchTask.class.getName();

    public BTSearchTask(BTSearchAdapter adapter){
        super(adapter);
    }


    @Override
    protected String getCacheKey() {
        return null;
    }

    @Override
    public BTSearchResultsListResponse run(BTSearchClientParameters params)  throws Exception{
            BTSearchClient client = ServiceClientFactory.getClient(BTSearchClient.class);

            final String taskid;
            if(!params.isStarted()){
                Log.d(TAG, "Starting search --> ");
                publishProgress("Starting search...");
                BTSearchStartResponse startResponse = client.start(params.getKeyword());
                if(startResponse.isSuccess())
                    taskid = startResponse.getData().getTaskid();
                else{
                    taskid = null;
                    //TODO: manage start error
                }
            }else
                taskid = params.getTaskid();


            publishProgress("Querying torrent search engines " + params.getCounter());
            BTSearchResultsListResponse resp = client.list(taskid);
            if(!resp.isSuccess()){
                resp.setSuccess(true);
                resp.setData(new BTSearchResultsDataObject());
                resp.setError(new ErrorObject());
                resp.getError().setCode(ApiErrorCode.retry.getErrorCode());
            }
            resp.getData().setTaskid(taskid);

            return resp;

    }

    @Override
    protected void onPostExecute(BTSearchResultsListResponse response) {
        BTSearchAdapter adapter = (BTSearchAdapter)getAdapter();
        adapter.setFinished(response.getData().isFinished());
        adapter.setTaskId(response.getData().getTaskid());

        super.onPostExecute(response);


    }
}
